package ss.pku.meeting.service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import lava.rt.expcption.PersistenceExecption;
import lava.rt.persistence.sql.SqlDataContextExecption;
import ss.pku.meeting.dc.MeetingDataContext;
import ss.pku.meeting.dc.MeetingDataContext.MeetingRoom;
import ss.pku.meeting.dc.MeetingDataContextRepository;
import ss.pku.meeting.dto.MeetingEvent;
import ss.pku.meeting.dto.MeetingResource;

@Service
public class MeetingCalendarService {
	
	@Autowired
	private MeetingDataContextRepository meetingDataContextRepository;

	private static MeetingDataContextRepository.Criteria CR=MeetingDataContextRepository.CRITERIA;
	
	
	public List<MeetingEvent> getEvents(Date startAt, Date endAt) throws PersistenceExecption {
		Objects.requireNonNull(startAt);
		Objects.requireNonNull(endAt);
		List<MeetingEvent> rets=new ArrayList<>();
		String where=CR.start.between(null, null);
		List<MeetingDataContext.MeetingEvent> events=meetingDataContextRepository.MEETING_EVENT.selectList( where, "", 0, Integer.MAX_VALUE,startAt,endAt);
		for(MeetingDataContext.MeetingEvent event : events) {
			MeetingEvent ret=MeetingEvent.fromEntity(event);
			rets.add(ret);
		}
		return rets;
	}


	public List<MeetingResource> getEffectiveResources() throws PersistenceExecption {
		List<MeetingResource> rets=new ArrayList<>();
		String where=CR.roomStatus.eq(null);
		List<MeetingRoom> rooms=meetingDataContextRepository.MEETING_ROOM.selectList(where, CR.roomId.asc, 0, Integer.MAX_VALUE,1);
		rooms.stream().forEach(room->{
			MeetingResource ret=new MeetingResource();
			ret.setId(room.getRoomId().toString());
			ret.setTitle(room.getRoomNo());
			rets.add(ret);
		});
		return rets;
	}


	public int createEvent(MeetingEvent body) throws SqlDataContextExecption, ParseException {
		MeetingDataContext.MeetingEvent event=MeetingEvent.toEntity(body);
		int ret=meetingDataContextRepository.MEETING_EVENT.insert(event);
		return ret;
	}


	public int updateEvent(MeetingEvent body) throws SqlDataContextExecption, ParseException {
		// TODO Auto-generated method stub
		MeetingDataContext.MeetingEvent event=MeetingEvent.toEntity(body);
		int ret=meetingDataContextRepository.MEETING_EVENT.update(event);
		return ret;
	}



	public int deleteEvent(String id) throws SqlDataContextExecption {
		// TODO Auto-generated method stub
		int ret=meetingDataContextRepository.MEETING_EVENT.delete(CR.id.eq(null), id);
		return ret;
	}


	public MeetingEvent getEventById(String id) throws SqlDataContextExecption {
		MeetingEvent ret=null;
		MeetingDataContext.MeetingEvent event=meetingDataContextRepository.MEETING_EVENT.loadByPk(id);
		ret=MeetingEvent.fromEntity(event);
		return ret;
	}

	
}
